<template>
  <div id="SelectMultDataGrid">
    <vxe-pulldown ref="pulldownRef" transfer>
      <template #default>
        <vxe-input ref="SelectInpiut" v-model="inputValue" :style="{ width: props.inputWidth }" suffix-icon="vxe-icon-table" :placeholder="props.placeholder" @suffix-click="suffixClick" @focus="focusEvent" @change="findDataList" @blur="blurEvent"></vxe-input>
      </template>

      <template #dropdown>
        <div class="my-bodydown4" :style="{ width: width, height: height }">
          <vxe-table border ref="tableRef" :data="dataList" height="auto" width="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: false }">
            <vxe-column type="checkbox" width="60"></vxe-column>
            <!-- <vxe-column field="code" title="编号"></vxe-column>
            <vxe-column field="name" title="名称"></vxe-column> -->
            <vxe-column v-for="(item, index) in props.column" :key="index" :field="item.field" :title="item.title"></vxe-column>
          </vxe-table>
          <div class="saveButton">
            <vxe-button type="text" status="primary" content="确认" style="background-color: #409eff; color: #fff; margin-top: 10px" @click="confirmBtnEvent"></vxe-button>
          </div>
        </div>
      </template>
    </vxe-pulldown>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, onMounted, watch } from 'vue';
import { pageSizes, IsEmpty } from '../utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { log } from 'console';
import { includes } from 'lodash';
// import { watch } from 'fs';
defineExpose({
  findDataList,
  suffixClick,
  initBaseText
});
let indexarr = [];
let props = defineProps({
  url: String, //请求地址
  column: Array as () => String[], //动态列和字段名
  searchParam: {}, //接口参数{key1:value1,key2:value2...}
  isPage: { type: Boolean, default: false }, //是否需要分页
  width: { type: String, default: '590px' }, //表格宽度
  height: { type: String, default: '300px' }, //表格高度
  inputKeyName: String, //查询入参名称
  placeholder: { type: String, default: '点击选择' }, //弹框标题
  clickRowId: String, //选中表格行的id
  showField: { type: String, default: 'name' }, //点击确定按钮后 输入框展示选中行的哪一个字段
  inputWidth: { type: String, default: '200px' } //输入框长度
}) as any;
let inputValue = ref('');
let sLoading = ref(false);
let { proxy }: any = getCurrentInstance();
let dataList = reactive([]);
let tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: pageSizes[0]
});

function findDataList() {
  dataList.length = 0;
  sLoading.value = true;
  // 请求参数
  let params: any = {
    pageSize: tablePage.pageSize,
    pageIndex: tablePage.currentPage,
    orgId: ''
  };

  // 循环父组件传来的参数，添加到参数对象中(data，params)
  if (!IsEmpty(props.searchParam)) {
    for (const key in props.searchParam) {
      if (props.searchParam[key]) {
        params[key] = props.searchParam[key];
      }
    }
  }

  if (!IsEmpty(props.inputKeyName)) {
    params[props.inputKeyName] = inputValue.value;
  }
  proxy.$http
    .get(props.url, { params })
    .then((res: any) => {
      sLoading.value = false;
      if (res.status.code !== 1 && res.status.code !== 200) {
        VxeMessage('获取列表失败', VxeNotifyType.error);
      } else {
        dataList.length = 0;
        if (props.isPage) {
          dataList.push(...res.data.records);
          tablePage.total = res.data.total;
        } else {
          dataList.push(...res.data);
        }

        if (props.clickRowId && props.clickRowId.length > 0) {
          proxy.$nextTick(() => {
            btnClickHandler();
          });
        }
        // inputValue.value = props.clickRowId;
      }
    })
    .catch((err) => {
      sLoading.value = false;
      VxeMessage('获取列表失败', VxeNotifyType.error);
    });
}
//装饰器中的参数是方法名，用来传递给父组件
function handleClickRow({ row }) {
  proxy.$emit('selectDataRow', row);
}

// 输入框获取焦点
let pulldownRef = ref();
let SelectInpiut = ref();
function focusEvent() {
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.showPanel();
  }
  findDataList();
}

// 点击确认按钮
function btnClickHandler() {
  const idsArr = props.clickRowId.split(',');

  const selectedRows = idsArr.map((id) => dataList.find((el) => el.id === id || (el.code && el.code === id)));

  //获取焦点后 将选中的名字 赋值给输入框
  const newNameArr = [];
  selectedRows.forEach((item) => {
    newNameArr.push(item[props.showField]);
  });
  inputValue.value = newNameArr.join(',');

  const $table = proxy.$refs.tableRef;
  if ($table) {
    $table.setCheckboxRow(selectedRows, true);
  }
}

function setSelectRow(rows, checked) {
  const $table = proxy.$refs.tableRef;
  if ($table) {
    $table.setCheckboxRow(rows, checked);
  }
  indexarr = [];
}
// [tableData[2], tableData[3]];
// 输入框点击
function suffixClick() {
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.togglePanel();
  }
}

// 输入框失去焦点
function blurEvent() {
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.showPanel();
  }
}

// 点击确定按钮
function confirmBtnEvent() {
  const checkedBoxRow = proxy.$refs.tableRef.getCheckboxRecords();

  const nameArr = [];
  checkedBoxRow.forEach((item) => {
    nameArr.push(item[props.showField]);
  });
  const nameString = nameArr.join(',');
  inputValue.value = nameString; //输入框赋值
  proxy.$emit('SelectCellClick', checkedBoxRow);

  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.togglePanel();
  }
}

// 页数变更
function pageChangeEvent({ type, currentPage, pageSize }) {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  findDataList();
}
/**设置初始值显示 */
function initBaseText(valStr: String) {
  inputValue.value = valStr;
}
</script>
<style lang="scss" scoped>
#SelectMultDataGrid {
  .saveButton {
    width: 100%;
    text-align: right;
  }
  :deep(.vxe-pulldown) {
    width: 100%;
  }
  :deep(.vxe-table--render-default .vxe-cel) {
    line-height: 19px !important;
  }
}
</style>
